package com.hs.telepass.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.*;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import com.hs.teleform.R;
import com.hs.telepass.Constants;
import com.hs.telepass.dao.SingouProfilesDatabase;
import com.hs.telepass.dao.TelepassProfilesDatabase;
import com.hs.telepass.manager.PreferencesManager;
import com.hs.telepass.model.Profile;
import com.hs.telepass.utils.StringUtil;
import com.hs.telepass.utils.ToastUtil;

public class EditUserInfoActivity extends BaseActivity {

    @InjectView(R.id.edtText_username)
    EditText mEdtTextUsername;
    @InjectView(R.id.edtText_password)
    EditText mEdtTextPassword;
    @InjectView(R.id.button_commit)
    Button mButtonCommit;
    @InjectView(R.id.txtview_hostname)
    TextView mTxtviewHostname;
    @InjectView(R.id.cb_remember_password)
    CheckBox mSwitchLogin;
    @InjectView(R.id.btn_cancel)
    Button mBtnCancel;
    @InjectView(R.id.btn_delete)
    Button mBtnDelete;
    @InjectView(R.id.btn_eye)
    ImageButton mBtnEye;

    public static final int INTENT_RESULT_EYE = 0;

    private Context mContext;
    private PreferencesManager mPreferencesManager;
    private Profile mProfile;

    /**
     * 判断来源于singou 还是 teleform
     */
    private int mSource;

    @OnClick(R.id.button_commit)
    void commit() {
        String username = mEdtTextUsername.getText().toString();
        String password = mEdtTextPassword.getText().toString();
        boolean isChecked = mSwitchLogin.isChecked();

        if (StringUtil.isEmpty(username)) {
            ToastUtil.showMessageInShort(mContext, R.string.input_commit_empty);
        } else {
            //如果开关为关闭时,则清空密码
            if (!isChecked)
                password = "";

            //存储账号密码
            if (isFromSingou()) {
                new SingouProfilesDatabase(mContext).updateProfile(mProfile.getId(), username, password);
            } else {
                new TelepassProfilesDatabase(mContext).updateProfile(mProfile.getId(), username, password);
            }
            ToastUtil.showMessageInShort(mContext, R.string.edit_success);
            finish();
        }

    }

    @OnClick(R.id.btn_eye)
    void watchEyeClick(){
        if(mPreferencesManager.getUserHasInitPsw()){
            showInputSingouPswDialog();
        }else{
            Intent intent = new Intent(mContext, SingouPasswordActivity.class);
            intent.putExtra(SingouPasswordActivity.EXTRA_HAS_SINGOU_PASSWORD, false);
            startActivityForResult(intent, INTENT_RESULT_EYE);
        }

    }

    @OnClick(R.id.btn_cancel)
    void backClick() {
        finish();
    }

    @OnClick(R.id.btn_delete)
    void deleteClick() {
        showSecurityDialog(mProfile.getId());
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_info_activity);
        ButterKnife.inject(this);

        mContext = EditUserInfoActivity.this;
        mPreferencesManager = PreferencesManager.getInstance();
        mProfile = (Profile) getIntent().getSerializableExtra(HistoryFragment.EXTRA_PROFILE);
        mSource = mProfile.getSource();

        initViews();
    }


    private void initViews() {
        mTxtviewHostname.setText(mProfile.getTitle());
        mEdtTextUsername.setText(mProfile.getUsername());
        mEdtTextPassword.setText(mProfile.getPassword());

        if (!StringUtil.isEmpty(mEdtTextPassword.getText().toString()))
            mSwitchLogin.setChecked(true);
    }

    @Override
    public IntentFilter getIntentFilter() {
        return null;
    }

    @Override
    public void handleOnReceive(Intent intent) {

    }


    @Override
    public void finish() {
        super.finish();
//        this.overridePendingTransition(R.anim.activity_close,0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(INTENT_RESULT_EYE == requestCode){
            showInputSingouPswDialog();
        }
    }

    private boolean isFromSingou() {
        return Constants.SOURCE_SINGOU == mSource;
    }

    /**
     * 弹出输入安全档案的框
     */
    private void showSecurityDialog(final int id) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.tip_ask_delete))
                .setIcon(android.R.drawable.ic_dialog_info)
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int effectedRows;
                        if (isFromSingou())
                            effectedRows = new SingouProfilesDatabase(mContext).deleteProfile(id);
                        else
                            effectedRows = new TelepassProfilesDatabase(mContext).deleteProfile(id);

                        if (0 < effectedRows)
                            ToastUtil.showMessageInShort(mContext, R.string.tip_delete_success);
                        else
                            ToastUtil.showMessageInShort(mContext, R.string.tip_delete_fail);

                        finish();
                    }
                });

        final AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void showInputSingouPswDialog() {
        LayoutInflater inflater = LayoutInflater.from(context);
        View dialogView = inflater.inflate(R.layout.security_profile_dialog, null);
        final EditText editText = (EditText) dialogView.findViewById(R.id.proifle_username);

        /**下面的写法能够控制dialog消失*/
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.title_input_password))
                .setIcon(android.R.drawable.ic_dialog_info)
                .setView(dialogView)
                .setNegativeButton("Cancel", null)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });

        final AlertDialog dialog = builder.create();
        dialog.show();

        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String realPassword = PreferencesManager.getInstance().getPasswordKey();
                String password = editText.getText().toString();
                if(StringUtil.isEmpty(password) || !realPassword.equals(password)){
                    ToastUtil.showMessageInShort(mContext, R.string.tip_input_right);
                }else {
                    mEdtTextPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                dialog.dismiss();
            }
        });
        ;

    }

}